﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace ThiefRun.Util.Keyboards
{
    public class KeyboardAction
    {
        #region Constants
        // Constants
        #endregion Constants

        #region Properties
        // Properties
        private List<Keys> keys;
        public delegate void Action();
        private Action action;
        bool pressed;
        #endregion Properties

        #region Computed Properties
        // Computed Properties
        #endregion Computed Properties

        #region Methods
        // Methods

        /// <summary>
        /// Initialize a KeyboardAction.
        /// </summary>
        /// <param name="keys">The keys that need to be pressed.</param>
        /// <param name="action">The function to execute when the keys are pressed.</param>
        public KeyboardAction(List<Keys> keys, Action action)
        {
            this.keys = keys;
            this.action = action;
            this.pressed = false;
        }

        /// <summary>
        /// Check if the keys were pressed.
        /// </summary>
        /// <returns>True if the keys were pressed. False, otherwise.</returns>
        private bool WasPressed()
        {
            // Prevent spamming of keys.
            //if (pressed)
                //return false;

            foreach (Keys key in keys)
            {
                // The key was not pressed.
                if (!Keyboard.GetState().IsKeyDown(key))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Check if the keys were released.
        /// </summary>
        /// <returns>True if all of the keys are released. False, otherwise.</returns>
        private bool WasReleased()
        {
            foreach (Keys key in keys)
            {
                // The key was not pressed.
                if (!Keyboard.GetState().IsKeyUp(key))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Called whenever a key must be checked.
        /// </summary>
        /// <param name="gameTime"></param>
        public void Update(GameTime gameTime)
        {
            // The keys were pressed.
            if (WasPressed())
            {
                action();
                pressed = true;
            }

            // The keys were released.
            if (WasReleased())
                pressed = false;
        }

        #endregion Methods
    }
}
